var app = getApp();
//常量数据配置
var ConstantData = require('../../common/constant_data.js')
var BLELocker = require('../../common/BLELocker.js')
var common = require('../../common/common.js')


/**
 * 连接设备
 */
function connectDev(mac, that) {
  if(typeof that.getConnectShowObj == 'function') {
     let conShowObj = that.getConnectShowObj()
     conShowObj.networkConnecting()
  }
  that.data.openBlueAdapterFail = true;
  that.data.isColonyCon = true;
  app.globalData.beforeConIsGateway = true;
  that.setData({
    openning_show: false,
    connectDesc: "请稍等,网关连接中...",
    loading_show: true,
    loading_desc: '请稍等,网关连接中...',
  });
  let isWxScan = that.data.isWxScanFlg ? "wxScan" : "ejiaScan";
  that.recordBlueConnectError(ConstantData.err_type.new_con, 'gateway start connect:' + isWxScan);

  let reqConTimeout = setTimeout(() => {

    if (!that.data.pile_id) {
      that.data.pile_id = app.globalData.curConHid;
    }
    if(app.globalData._that && typeof app.globalData._that.hideAllShow == 'function') {
      app.globalData._that.hideAllShow()
      app.globalData._that.cleanTimer()
    }
    that.setData({
      showModalStatus: false,
      mapShowStatus: true,
      loading_show: false,
      firstConFail: true,
      modal: {
        modal_show: true,
        desc_mini: '网关超时' + that.data.pile_id?that.data.pile_id:'' + '-' + ConstantData.err_type.data_95_send_timeout,
        desc: '连接失败,点击重试',
        retryConnect: true
      }
    });
    gatewayDisCon(that, 'colonyTiemout_50')
    that.recordBlueConnectError(ConstantData.err_type.gateway_con_timeout, 'gateway con timeout');
    var now = new Date().getTime();
    app.globalData.gatewayFail = now;
    common.storeWxClientType(that);

  }, app.globalData.gatewayConTimeout);

  let startTime = new Date().getTime()
  //用于进行归还处理
  let noBackEqId = that.data.noBackEqId ? that.data.noBackEqId : 0;
  app.executeRequest(function (header) {

    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/bluecolony/connect',
      method: 'post',
      header: header,
      timeout: app.globalData.gatewayConTimeout,
      data: {
        mac: mac,
        noBackEqId: noBackEqId
      },
      success: function (res) {
        let timeLen = new Date().getTime() - startTime
        console.log("=====gateway_con======res=", res, mac, ';timeLen=' + timeLen)
        that.recordBlueConnectError(ConstantData.err_type.gateway_con_time_len, 'ct:' + timeLen + ';' + JSON.stringify(res.data));
        var data = res.data;
        let isOk = data.result == 0 && data.data && (!data.data.rfid || data.data.rfid != 'null' || data.data.rfid != '');
        if (isOk) {       
          app.globalData.devConnected = true
          //连接成功的类型
          app.globalData.connectSucType = 'gateway'   
          //获取成功
          that.handleStatus(BLELocker.Status.ble95Data, data.data);
        } else {      
          that.data.leaseShow.resultShow('网关连接失败(' + data.result + ":" + data.description + ')')         
          common.storeWxClientType(that);
          that.recordBlueConnectError(ConstantData.err_type.gateway_con_fail, 'gateway con fail');
        }
      },
      complete:function()  {
        clearTimeout(reqConTimeout)          
      }
    });

  });


}

/**
 * 网关连接失败后5分钟内扫码，改用蓝牙连接
 * @returns {} true 使用蓝牙连接，false使用网关连接
 */
function isGatewayFailBleCon() {
  let failTime = getApp().globalData.gatewayFail;
  var diff = 0;
  if (failTime) {
    diff = new Date().getTime() - failTime;
  }
  var flg = diff > 0 && diff < app.globalData.gatewayFailBleConTime;
  if (flg) {
    common.storeWxClientType(app.globalData._that);
  } else {
    common.storeGatewayClientType();
  }
  return flg;
}

/**
 * 蓝牙连接失败后5分钟内扫码，改用网关连接
 * @returns {} true 使用网关连接，false 不是用网关
 */
function isBleFailGatewayCon() {
  let failTime = getApp().globalData.bleConFail;
  var diff = 0;
  if (failTime) {
    diff = new Date().getTime() - failTime;
  }
  console.log("isBleFailGatewayCon--->diff=", diff, failTime);
  var flg = diff > 0 && diff < app.globalData.gatewayBleFailConTime;
  if (!flg) {
    common.storeWxClientType(app.globalData._that);
  } else {
    common.storeGatewayClientType();
  }
  return flg;
}

/**
 * 蓝牙连接失败存储时间
 */
function bleConFailMark() {
  var now = new Date().getTime();
  getApp().globalData.bleConFail = now;
}

/**
 * 是否可以网关连接
 * @param {} that
 * true 使用网关 false 不是用网关 
 */
function isGatewayCon(that) {
  //网关连接失败后5分钟内扫码，改用蓝牙连接，true使用蓝牙连接
  let isBleCon = isGatewayFailBleCon();
  //蓝牙连接失败后5分钟内扫码，改用网关连接，true使用网关连接
  let isGatewayCon = isBleFailGatewayCon();
  let hpIsColony = that.data.hpIsColony;
  //是否可直接使用节点
  var colonyIsDirectUse = hpIsColony == 1;
  //是否在连接失败后使用
  var colonyIsFailUse = hpIsColony == 2;
  if (colonyIsFailUse && isGatewayCon) {
    colonyIsDirectUse = true;
  }

  cleanFailMark();

  console.log("isGatewayCon stat ",isBleCon, isGatewayCon, hpIsColony , colonyIsDirectUse)
  var flg = !isBleCon && colonyIsDirectUse;
  if (!flg) {
    common.storeWxClientType(that);
  } else {
    common.storeGatewayClientType();
  }
  return flg;
}

function cleanFailMark(){
  getApp().globalData.gatewayFail = null;
  getApp().globalData.bleConFail  = null;
}

/***
 * 开锁
 */
function openLock(mac, that) {
  that.data.openBlueAdapterFail = true;
  app.globalData.gatewayUnlockFlg = true 
  that.recordBlueConnectError(ConstantData.err_type.data_85_send, 'gateway开始发送85:');
  if(app.globalData.timeoutGatewayUnlockTimer) {
    clearTimeout(app.globalData.timeoutGatewayUnlockTimer)
  }
  let reqUnLockTimeout = setTimeout(() => {
    that.setData({
      openning_show: false
    });

    if (!that.data.pile_id) {
      that.data.pile_id = app.globalData.curConHid;
    }
    app.globalData.devConnected = true;
    that.data.no_eject_back_flg = 1;
    that.handleStatus(BLELocker.Status.ble85Back1Timeout, null);
  }, app.globalData.gatewayUnlockTimeout);

  app.globalData.timeoutGatewayUnlockTimer = reqUnLockTimeout

  app.executeRequest(function (header) {

    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/bluecolony/unlock',
      method: 'post',
      header: header,
      timeout: app.globalData.gatewayUnlockTimeout,
      success: function (res) {
        console.log("--是否直接连蓝牙", res);
        var rst = res.data.result;
        if (rst == 1000) {
          wx.showToast({
            title: '请重试',
          });

          that.setData({
            openning_show: false
          })
          return;
        } else if (rst == 1001) {          
          that.setData({
            openning_show: false,
            alertBoxStatus: true,
            alertBoxTipContent: '开锁失败,请重试',
            alertBoxBtnName: '确  定'
          });
          return;
        } else if (rst != 0) {
          wx.showToast({
            title: '蓝牙重试中',
          });
          
          that.setData({
            openning_show: false,
            loading_desc: "蓝牙连接中",
            loading_show: true,
            agentLeaseSelStatus: false,
            showModalStatus: false,
            isColonyCon: false
          })
          //集群已被使用，使用蓝牙进行连接
          that.connectBLEDevice("DK" + mac);
          return;
        }

        if (rst == 0) {
          that.setData({
            openning_show: false
          })
          that.handleStatus(BLELocker.Status.ble88Data, res.data.data);
        } else {
          common.storeWxClientType(that);
          that.setData({
            loading_show: false,
            openning_show: false,
            connectDesc: ""
          });
          wx.showToast({
            title: '开锁失败',
            duration: 2500
          })
        }

      },
      fail: function (res) {
      },
      complete: function(){
        //开锁结果后取消超时定时器
        clearTimeout(reqUnLockTimeout);
      }
    });

  });

}


/***
 * 断开与控制盒的连接
 */
function gatewayDisCon(that, lineNum) {
  if (!that || !that.data.isColonyCon) {
    return;
  }
  let connected = app.globalData.devConnected;  
  let isTimeout = app.globalData.gatewayUnlockFlgTime ? new Date().getTime() - app.globalData.gatewayUnlockFlgTime >= 30000 : false;
  let isDisCon = !app.globalData.gatewayUnlockFlg || isTimeout;
  let txt = isDisCon ? 'gateway断开连接:'  : 'gateway开锁中,暂不断开:';
  that.recordBlueConnectError(ConstantData.err_type.gateway_discon_flg, txt + connected + "," + (lineNum ? lineNum : 0) + "," + isDisCon + "," + isTimeout);
  if(isDisCon) {
    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/bluecolony/disCon',
        method: 'post',
        header: header,
        success: function (res) {          
        },
        fail: function (res) {          
        },
        complete: function(){
          if(that.data.disCompleteConFlg) {      
            if(that.startGatewayConnect instanceof Function) {
              that.startGatewayConnect()
            }else {
              that.data.disCompleteConFlg = false
              wx.showToast({
                title: '扫码重试',
              })
              wx.redirectTo({
                url: '/pages/index/index',
              })
            } 
          }
          that.data.disCompleteConFlg = false
        }
      });
  
    });  
  }
  
}



module.exports.connectDev = connectDev
exports.openLock = openLock
exports.isGatewayFailBleCon = isGatewayFailBleCon
exports.bleConFailMark = bleConFailMark
exports.isBleFailGatewayCon = isBleFailGatewayCon
exports.isGatewayCon = isGatewayCon
exports.gatewayDisCon = gatewayDisCon
exports.cleanFailMark = cleanFailMark